package com.qinggeng.project.api.security.interceptor;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Maps;
import com.qinggeng.common.constant.Constants;
import com.qinggeng.common.enums.ShowTypeEnum;
import com.qinggeng.common.enums.StatusEnum;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.StringUtils;
import com.qinggeng.framework.redis.RedisCache;
import com.qinggeng.framework.security.LoginUser;
import com.qinggeng.framework.web.domain.AjaxResult;
import com.qinggeng.project.api.security.annotation.LoginRequired;
import com.qinggeng.project.api.security.utils.ApiUtils;
import com.qinggeng.project.api.service.IApiMemberService;
import com.qinggeng.project.system.domain.SysUser;
import com.qiniu.util.Json;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

import static com.qinggeng.common.constant.Constants.API_TOKEN_KEY;
import static com.qinggeng.common.constant.Constants.API_TOKEN_ROLE_KEY;
import static com.qinggeng.common.constant.Constants.LOGIN_USER_KEY;

/**
 * 微信登录app拦截器
 */
@Slf4j
@Component
public class ApiLoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IApiMemberService memberService;

    Map<String,String> result ;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        LoginRequired annotation;
        if (handler instanceof HandlerMethod){
            annotation =  ((HandlerMethod) handler).getMethodAnnotation(LoginRequired.class);
            if (annotation != null){
                //解决跨域问题
                response.addHeader("Access-Control-Allow-Origin", "*");
                response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
                response.addHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
                response.addHeader("Access-Control-Max-Age", "3600");
            }
        }else {
            // 如果不是映射到方法直接通过
            return true;
        }
        //如果不需要登陆验证，直接通过
        if(annotation == null){
            return true;
        }

        //需要验证，获取用户凭证
        String token = request.getHeader(Constants.TOKEN);

        if(StringUtils.isBlank(token)){
            token = request.getParameter(Constants.TOKEN);
        }

        if (!annotation.must() && StringUtils.isBlank(token)){
            return true;
        }

        //凭证为空
        if(StringUtils.isBlank(token)){
            throw new CustomException(HttpStatus.UNAUTHORIZED.value(),"无token，请重新登录", ShowTypeEnum.后台.getValue());
        }
        //验证token
        LoginUser loginUser = redisCache.getCacheObject(getToken(token));

        if(!annotation.must() && loginUser == null){
            return true;
        }

        if(loginUser == null){
            throw new CustomException(HttpStatus.UNAUTHORIZED.value(),"凭证失效，请重新登录",ShowTypeEnum.用户.getValue());
        }

        try {
            String role= redisCache.getCacheObject(getRoleToken(token));
            if(StringUtils.isEmpty(role)){
                throw new CustomException("权限不足无法请求此接口");
            }
            if (!annotation.role().equals("all") &&  !role.equals(annotation.role())){
                throw new CustomException("权限不足无法请求此接口");
            }
        }catch (Exception e){
            log.error("权限不足无法请求此接口{}",e.getMessage());
            throw new CustomException(HttpStatus.UNAUTHORIZED.value(),"请重新登录",ShowTypeEnum.用户.getValue());
        }


        SysUser user = memberService.selectMemberById(loginUser.getUser().getUserId());
        if (user == null) {
            throw new CustomException(HttpStatus.UNAUTHORIZED.value(),"用户不存在，请重新登录",ShowTypeEnum.用户.getValue());
        }
        if (user.getStatus().equals(StatusEnum.DISABLE.getCode())){
            throw new CustomException(HttpStatus.UNAUTHORIZED.value(),"账号已停用，请联系管理员",ShowTypeEnum.用户.getValue());
        }
        loginUser.setUser(user);

        redisCache.setCacheObject(getToken(token), loginUser, Constants.API_TOKEN_EXPIRY, Constants.API_TOKEN_TIMEUNIT);
        redisCache.setCacheObject(getRoleToken(token),loginUser.getRole(),Constants.API_TOKEN_EXPIRY,Constants.API_TOKEN_TIMEUNIT);


        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(Constants.API_USERID, getToken(token));
        return true;
    }

    private String getToken(String token){
        return API_TOKEN_KEY+ token;
    }

    private String getRoleToken(String token) {
        return API_TOKEN_ROLE_KEY + token;
    }

}
